package com.emapp.lccode.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.annotation.RequiresApi
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.emapp.lccode.R
import com.emapp.lccode.base.BaseApplication
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.interfaces.OnBitmapWatermarkEventListener
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.DensityUtil
import com.luck.picture.lib.utils.PictureFileUtils
import org.jetbrains.annotations.Nullable
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 *@Description: 给图片添加水印
 *@Author:  zhang
 *@Date:   2023/8/4
 */
class MeBitmapWatermarkEventListener(private val targetPath: String,val content: String) :
    OnBitmapWatermarkEventListener {
    override fun onAddBitmapWatermark(
        context: Context,
        srcPath: String,
        mimeType: String,
        call: OnKeyValueResultCallbackListener
    ) {
        if (PictureMimeType.isHasHttp(srcPath) || PictureMimeType.isHasVideo(mimeType)) {
            // 网络图片和视频忽略，有需求的可自行扩展
            call.onCallback(srcPath, "")
        } else {
            // 暂时只以图片为例
            Glide.with(context).asBitmap().sizeMultiplier(0.6f).load(srcPath)
                .into(object : CustomTarget<Bitmap?>() {
                    @RequiresApi(Build.VERSION_CODES.M)
                    override fun onResourceReady(
                        resource: Bitmap,
                        @Nullable transition: Transition<in Bitmap?>?
                    ) {
                        val stream = ByteArrayOutputStream()
//                            val watermark = BitmapFactory.decodeResource(
//                                context.resources,
//                                com.emapp.lccode.R.drawable.ic_mark_win
//                            )
                        var content0= "  $content  ${SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date())}"
                        val watermark = textToBitmapWithWrapping(content0, 50f)
                        val watermarkBitmap: Bitmap? = ImageUtil.createWaterMaskRightTop(
                            context,
                            resource,
                            watermark,
                            15,
                            15
                        )
                        watermarkBitmap?.compress(Bitmap.CompressFormat.JPEG, 60, stream)
                        watermarkBitmap?.recycle()
                        var fos: FileOutputStream? = null
                        var result: String? = null
                        try {
                            val targetFile =
                                File(targetPath, DateUtils.getCreateFileName("Mark_") + ".jpg")
                            fos = FileOutputStream(targetFile)
                            fos.write(stream.toByteArray())
                            fos.flush()
                            result = targetFile.absolutePath
                        } catch (e: IOException) {
                            e.printStackTrace()
                        } finally {
                            PictureFileUtils.close(fos)
                            PictureFileUtils.close(stream)
                        }
                        if (call != null) {
                            call.onCallback(srcPath, result)
                        }
                    }

                    override fun onLoadCleared(@Nullable placeholder: Drawable?) {
                        if (call != null) {
                            call.onCallback(srcPath, "")
                        }
                    }
                })
        }
    }

    fun textToBitmap(text: String, size: Float): Bitmap {
        val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.BLACK
            textAlign = Paint.Align.LEFT
            textSize = size
        }

        val baseline = -paint.ascent() // 计算文本基准线的位置
        val width = (paint.measureText(text) + 0.5f).toInt() // 计算文本的宽度
        val height = (baseline + paint.descent() + 0.5f).toInt() // 计算文本的高度

        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        canvas.drawColor(Color.WHITE) // 设置画布背景色
        canvas.drawText(text, 0f, baseline, paint) // 在画布上绘制文本

        return bitmap
    }
    @RequiresApi(Build.VERSION_CODES.M)
    fun textToBitmapWithWrapping(text: String, size: Float, maxWidth: Int= (DensityUtil.getRealScreenWidth(BaseApplication.instance)/1.5).toInt()): Bitmap {
        val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.BLACK
            textAlign = Paint.Align.LEFT
            textSize = size
        }

        // 使用StaticLayout来处理换行
        val layout = StaticLayout.Builder.obtain(text, 0, text.length, paint , maxWidth)
            .setAlignment(Layout.Alignment.ALIGN_NORMAL)
            .setLineSpacing(0f, 1f) // 设置行间距（可选）
            .setIncludePad(false) // 不包括额外的文本宽度（可选）
            .build()

        // 获取文本布局的高度
        val height = layout.height.toInt()

        // 创建一个足够大的Bitmap来容纳整个文本布局
        val bitmap = Bitmap.createBitmap(maxWidth, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)

        // 设置画布背景色
        canvas.drawColor(getColorExt(R.color.app_color_f0))

        // 使用StaticLayout绘制文本
        layout.draw(canvas)

        return bitmap
    }

    // 假设这个函数在一个Activity或Fragment中调用，或者传入了合适的Context
    fun getFullScreenMaxWidth(context: Context): Int {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)

        // displayMetrics.widthPixels 是屏幕的像素宽度
        // 如果你需要dp单位，可以使用以下转换（以160dpi为基准）
        val widthInDp = (displayMetrics.widthPixels / displayMetrics.xdpi).toInt()

        // 如果需要减去一些边距或填充，可以在这里做
        // 例如，减去16dp的左右边距
        val marginInDp = 10
        val maxWidthInDp = widthInDp - 2 * marginInDp

        // 如果需要px单位，可以转换回像素
        val marginInPx = (marginInDp * displayMetrics.xdpi / 160).toInt()
        val maxWidthInPx = displayMetrics.widthPixels - 2 * marginInPx

        // 返回全屏最大宽度（可以是dp或px单位，取决于你的需求）
        return maxWidthInPx // 或者 maxWidthInDp
    }
}